package leetcode.D100.T40;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> results = new LinkedList<>();
        Arrays.sort(candidates);
        List<Integer> path = new ArrayList<>(candidates.length); // 优化一
        dfs(results, path, candidates, target, 0, -1);
        return results;
    }
    private void dfs(List<List<Integer>> results, List<Integer> path, int[] candidates, int target, int sum, int current) {
        if(sum == target) {
            results.add(new ArrayList<>(path));
            return;
        }
        for(int i=current+1; i<candidates.length; ++i) {
            if(i>current+1 && candidates[i] == candidates[i-1]) {
                continue;
            }
            if(sum + candidates[i] > target) {
                break;
            }
            path.add(candidates[i]);
            dfs(results, path, candidates, target, sum+candidates[i], i);
            path.remove(path.size()-1);
        }
    }
}